var express = require('express');
// 后端路由，用于分配前端的请求
var router = express.Router();
//图片增加删除文件
const { moveFiles, removeFiles } = require('../utils/uploadFiles');

const { login, isAccess, register, getLessors } = require('../service/lessorsService');
// const { getMd5 } = require('./../utils/crypto');
const { compareSync, hashSync } = require('bcrypt');
const jwt = require('jsonwebtoken')

//登陆
router.post('/login', async function(req, res, next) {
    // 接收到前端发送的用户数据
    const { account, password } = req.body; // { username:'123', password: '456' }
    // const newpassword = getMd5(password)
    // const data = await login({ username, password: newpassword });
    const { data } = await login({ account });
    // console.log(data);
    const isOk = compareSync(password, data[0].password)
    if (isOk) {
        //设置令牌
        const token = jwt.sign({ _id: data[0]._id }, //这个数据是前端发送请求发过来的,可变,目的给前端一个可显示的数据
            'zhangsan', { expiresIn: 60 * 60 } //有效期 默认单位 秒
        );
        res.send({
            message: '登录成功',
            status: 1,
            token
        })
    } else {
        res.send({
            message: '登录失败,请重新输入',
            status: 0
        })
    }
    // res.send(data);
});
//注册
router.post('/register', async function(req, res, next) {
    const { account, password, phone, imagesName } = req.body;
    // const newpassword = getMd5(password)
    const newpassword = hashSync(password, 10)
    const data = await register({ account, password: newpassword, phone, imagesName });
    if (data.status && req.body.imagesName) {
        moveFiles({
            fromPath: `./public/temp`,
            toPath: `./public/images`,
            filename: req.body.imagesName
        });
        removeFiles('./public/temp')
    }
    res.send(data);
});



// 验证注册用户名是否重复
router.post('/isAccess', async function(req, res, next) {
    const { account } = req.body;
    // console.log();
    const data = await isAccess(account);
    res.send(data);
});

//检测登录携带token
router.get('/isLogin', async function(req, res, next) {
    const headerToken = req.get('Authorization');
    const token = headerToken.split(' ')[1];
    //解码 得到用户信息        解析token携带的秘钥
    const { _id } = jwt.verify(token, 'zhangsan');
    const result = await getLessors({ _id });
    res.send({
        message: '身份验证成功',
        status: 1,
        data: result
    })
});



/* GET home page. */
// 获取出租方信息
router.get('/getLessors', async function(req, res, next) {
    console.log('成功进入获取出租方信息第一层', req.query)
    const result = await getLessors(req.query);
    console.log('第一层获取出租方结果', result)
    res.send(result);
});
module.exports = router;